package top.jacktgq.itheima.nio.bio;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @Author CandyWall
 * @Date 2021/3/19--6:10
 * @Description
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 使用nio来理解阻塞模式
        // 0.ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 2.绑定监听端口
        ssc.bind(new InetSocketAddress(8080));

        // 3.建立连接集合
        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true) {
            log.debug("connecting...");
            // 4.接受请求，建立与客户端的连接,SocketChannel用来与客户端通信
            SocketChannel socketChannel = ssc.accept(); // 阻塞方法
            log.debug("connected..." + socketChannel);
            channels.add(socketChannel);
            // 5.接收客户端发送的数据
            for (SocketChannel channel : channels) {
                log.debug("before read..." + channel);
                channel.read(buffer); // 阻塞方法
                buffer.flip();
                System.out.println(StandardCharsets.UTF_8.decode(buffer));
                buffer.clear();
                log.debug("after read..." + channel);
            }
        }
    }
}
